package com.gmrz.uaf.protocol.v1.validaton;

import com.gmrz.uaf.common.Constants;
import com.gmrz.uaf.db.UAFDBConnectionMgr;
import com.gmrz.uaf.protocol.v1.processor.exception.UAFErrorCode;
import com.gmrz.uaf.protocol.v1.schema.FinalChallengeParams;
import com.gmrz.uaf.server.ServerConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Set;

public class FCParamsValidator
        implements Validator<FinalChallengeParams> {
    private static final Logger LOG = LogManager.getLogger(FCParamsValidator.class);
    private ServerConfig config;
    protected UAFDBConnectionMgr dbutil = null;
    private String tenantId;
    private String transType;


    public FCParamsValidator(ServerConfig config, String tenantId,String transType) {
        this.config = config;
        this.tenantId = tenantId;
        this.transType = transType;
    }


    public void validate(FinalChallengeParams fcp) throws ValidationException {

        Set<String> facetIDs = this.config.getFacetIDs(tenantId);

        String appID = fcp.getApplicationID();
        if (this.config.getAppIdUrlBoolean(tenantId,transType)) {
            int end = appID.lastIndexOf("/");
            String appIDEndStr = appID.substring(end);
            String appIdTemp = appID.substring(0, end);
            int start = appIdTemp.lastIndexOf("/");
            String appIDBeforeStr = appIdTemp.substring(0, start);
            appID = appIDBeforeStr + "/" + Constants.APP_ID + appIDEndStr;
            LOG.debug("paramappID:" + fcp.getApplicationID() + ",appID:" + appID);
        }
        boolean flag = false;
        if (null != appID && !"".equals(appID.trim())) {
            String serverAppId = this.config.getApplicationID(tenantId,transType);
            if (null != serverAppId && !"".equals(serverAppId.trim())) {
                if (this.config.getApplicationID(tenantId,transType).equals(appID)) {
                    flag = true;
                }
            } else {
                if (facetIDs.contains(appID)) {
                    flag = true;
                }
            }
        }
        if (!flag) {
            LOG.error("AppID[" + this.config.getApplicationID(tenantId,transType) + "] doesn't matches FCP AppID[" + appID + "]"
                    + " facetIDs[" + facetIDs + "]");
            throw new FCPValidationException(UAFErrorCode.PROTOCOL_APPID_VALIDATION_FAILED);
        }


        String facetID = fcp.getFacetID();

        if ((facetID == null) || (!facetIDs.contains(facetID))) {
            LOG.error("FacetID[" + facetID + "] not found in the set[" + facetIDs + "]");
            throw new FCPValidationException(UAFErrorCode.PROTOCOL_FACETID_VALIDATION_FAILED);
        }
    }
}
